<!--部门管路页-->
<template>
  <div class="head">
    <span class="headTitle">部门管理</span>
    <el-button class="headButton" type="primary" @click="newDepartment">新建部门</el-button>
  </div>
  <!-- 新建/积分操作 弹窗 -->
<el-dialog v-model="dialogNewDepartment" :title="dialogTitleDepartment"
           style="width: 40rem; padding: 2rem;"
           :before-close="closeDialog">
  <el-form label-width="80px" label-position="top">
    <!-- 新增/编辑部门 表单 -->
    <div v-if="dialogType === 'addDepartment' || dialogType === 'editDepartment'">
      <el-row>
        <el-col :span="24">
          <el-form-item label="部门名称">
            <el-input placeholder="请输入部门名称"
                      v-model="saveDepartmentForm.departmentName"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </div>

    <!-- 加分/减分 表单 -->
    <div v-else>
      <el-row :gutter="10">
        <el-col :span="11">
          <el-form-item label="部门名称">
            <el-input placeholder="请输入部门名称"
                      v-model="addScoreForm.departmentName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="2"></el-col>
        <el-col :span="11">
          <el-form-item :label="dialogType === 'add' ? '加分值' : '减分值'">
            <el-input placeholder="请输入分数"
                      v-model="addScoreForm.departmentScore"
                      :placeholder="dialogType === 'add' ? '请输入正数加分' : '请输入负数减分'"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="原因">
            <el-input placeholder="请输入操作原因"
                      v-model="addScoreForm.reason"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </div>
  </el-form>
  <template #footer>
    <el-button @click="closeDialog">取消</el-button>
    <el-button type="primary" @click="handleDialogConfirm">保存</el-button>
  </template>
</el-dialog>



  <!--用户搜索部门卡片-->
  <el-card class="findDepartment">
    <el-form :inline="true">
      <el-form-item label="用户搜索">
        <el-input placeholder="请输入部门名称" style="width: 45rem;"
                  v-model="searchDepartmentForm.departmentName"
                  @keydown.enter="loadDepartment"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button @click="resetDapartment">重置</el-button>
        <el-button class="buttonStyle" @click="loadDepartment">查询</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <!--部门数据表格卡片-->
  <el-card>
    <el-table :data="DepartmentForm">
      <el-table-column type="index" label="编号" width="80" align="center"></el-table-column>
      <el-table-column label="部门名称" align="center" prop="departmentName"></el-table-column>
      <el-table-column label="总分" align="center" prop="departmentScoreTotal"></el-table-column>
      <el-table-column label="周冠军" align="center" prop="departmentZGJCount"></el-table-column>
      <el-table-column label="月冠军" align="center" prop="departmentYGJCount"></el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button link type="success" @click="openScore('add', scope.row.departmentName)">加分</el-button>
          <el-button link type="warning" @click="openScore('subtract', scope.row.departmentName)">减分</el-button>
          <el-button link type="primary" @click="editDepartment(scope.row.departmentName)">编辑</el-button>
          <el-button link type="primary" @click="deleteDepartment">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>

<script setup>
import {ref, onMounted} from 'vue';
import qs from 'qs'
import axios from 'axios';
import {ElMessage} from "element-plus";
// import { ElMessage } from "element-plus";
//定义变量来控制弹窗的出现，默认是不弹出弹框的
const dialogNewDepartment = ref(false)

//定义变量为弹窗设置标题
const dialogTitleDepartment = ref('')
//定义对象来保存保存部门表单信息
const saveDepartmentForm = ref({
  departmentName: '',
  originalName: '', // 显式声明字段
  departmentId: '',
  departmentScoreTotal: '',
  departmentZGJCount: '',
  departmentYGJCount: ''
});


const addScoreForm = ref({
  departmentName: '',
  departmentScore: '',
  reason: ''
})

//定义对象来保存积分操作数据
let scoreForm = ref({})
//当点击新建部门的时候，弹出新建部门的弹窗
// const newDepartment = () => {
//   dialogNewDepartment.value = true
//   dialogTitleDepartment.value = '新增部门'
// }
//处理关闭弹窗的方法
const closeDialog = () => {
  if (confirm('确定要关闭该窗口吗？')) {
    dialogNewDepartment.value = false
  }
}

const DepartmentForm = ref([]);

//新建部门点击保存,对部门信息进行保存
const saveDepartment = () => {
  axios.post(BASE_URL + '/v1/departmentinfo/addDepartment?departmentName=' + saveDepartmentForm.value.departmentName,
      {
        headers: {
          'Content-Type': 'application/json'
          // Authorization: localStorage.getItem('token')
        }
      })
      .then(response => {
        if (response.data.code === 2000) {
          ElMessage.success("保存成功");
          //用户确认关闭后，关闭弹窗
          dialogNewDepartment.value = false;
          //清空已输入的表单数据
          saveDepartmentForm.value = {}
          loadDepartment();
        } else {
          ElMessage.error(response.data.msg);
        }
      })
      .catch(error => {
        console.error('Error:', error);
      });
  loadDepartment()
}

//定义加载部门列表的方法
// 定义对象来保存用户查询的条件
const searchDepartmentForm = ref({departmentName: ''})

const loadDepartment = () => {
  console.log(searchDepartmentForm.value)
  var data = qs.stringify(searchDepartmentForm.value)
  axios.get(BASE_URL + '/v1/departmentinfo/select2departmentName?' + data,
      {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        }
      }).then(res => {
    if (res.data.code == 2000) {
      console.log(res, '后端返回成功');
      DepartmentForm.value = res.data.data;
      console.log(res.data.data)
    } else {
      ElMessage.error(response.data.msg);
    }
  }).catch(error => {
    ElMessage.error(error, response.data.msg);
  })
}

// 页面一加载完毕,立即执行
onMounted(() => {
  loadDepartment();
})
//重置搜索
const resetDapartment = () => {
  //清空之前的搜索内容
  searchDepartmentForm.value = {}
  //重新加载所有部门数据
  loadDepartment()
}

//删除部门的方法
const deleteDepartment = (departmentName) => {
  if (confirm('您确认要删除该部门吗?')) {
    axios.post(BASE_URL + '/v1/departmentinfo/deleteDepartment' + departmentName)
        .then(res => {
          console.log(res)
          loadDepartment()
        }).catch(error => {
      console.log(error)
    })
  }
}

// 点击编辑部门
const editDepartment = (departmentName) => {
  dialogType.value = 'editDepartment'
  dialogTitleDepartment.value = '编辑部门 - ' + departmentName
  dialogNewDepartment.value = true
  
  // 保存原始部门名称用于后续比较
  saveDepartmentForm.value = {
    departmentName: departmentName,
    originalName: departmentName
  }
}

// //打开积分操作弹窗
// const openScore = () => {
//   //出现弹窗
//   dialogNewDepartment.value = true
//   //修改弹窗的标题
//   dialogTitleDepartment.value = '积分操作'
// }

// 控制弹窗显示的内容类型：'addDepartment', 'add', 'subtract', 'editDepartment'
const dialogType = ref('')

// 点击新增部门
const newDepartment = () => {
  dialogType.value = 'addDepartment'
  dialogTitleDepartment.value = '新增部门'
  dialogNewDepartment.value = true
  // 清空新增表单
  saveDepartmentForm.value = {}
}

// 点击加分或减分
const openScore = (type, departmentName) => {
  dialogType.value = type
  dialogTitleDepartment.value = '积分操作 - ' + (type === 'add' ? '加分' : '减分')
  dialogNewDepartment.value = true
  
  // 设置默认部门名称（仅用于加分/减分操作）
  if (departmentName) {
    addScoreForm.value.departmentName = departmentName
  } else {
    addScoreForm.value.departmentName = ''
  }
}

// 加分接口调用
const addDepartmentScore = () => {
  const data = {
    departmentName: addScoreForm.value.departmentName,
    departmentScore: parseInt(addScoreForm.value.departmentScore),
    reason: addScoreForm.value.reason
  }

  axios.post(BASE_URL + '/v1/departmentinfo/addDepartmentScore', qs.stringify(data), {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  })
  .then(response => {
    if (response.data.code === 2000) {
      ElMessage.success("加分成功");
      dialogNewDepartment.value = false;
      addScoreForm.value = {} // 清空表单
      loadDepartment(); // 刷新列表
    } else {
      ElMessage.error(response.data.msg);
    }
  })
  .catch(error => {
    console.error('加分失败:', error);
    ElMessage.error("加分失败，请重试");
  });
}

const handleDialogConfirm = () => {
  if (dialogType.value === 'add') {
    addDepartmentScore()
  } else if (dialogType.value === 'subtract') {
    subtractDepartmentScore()
  } else if (dialogType.value === 'addDepartment') {
    saveDepartment()
  } else if (dialogType.value === 'editDepartment') {
    updateDepartment()
  }
}

// 减分接口调用
const subtractDepartmentScore = () => {
  const data = {
    departmentName: addScoreForm.value.departmentName,
    departmentScore: parseInt(addScoreForm.value.departmentScore),
    reason: addScoreForm.value.reason
  }

  axios.post(BASE_URL + '/v1/departmentinfo/subtractDepartmentScore', qs.stringify(data), {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  })
  .then(response => {
    if (response.data.code === 2000) {
      ElMessage.success("减分成功");
      dialogNewDepartment.value = false;
      addScoreForm.value = {} // 清空表单
      loadDepartment(); // 刷新列表
    } else {
      ElMessage.error(response.data.msg);
    }
  })
  .catch(error => {
    console.error('减分失败:', error);
    ElMessage.error("减分失败，请重试");
  });
}

// 编辑部门保存
const updateDepartment = () => {
  // 校验输入
  if (!saveDepartmentForm.value.departmentName || !saveDepartmentForm.value.departmentName.trim()) {
    ElMessage.error('部门名称不能为空');
    return;
  }

  // 使用已保存的 originalName
  const originalName = saveDepartmentForm.value.originalName;

  // 调用后端接口
  axios.post(
    BASE_URL + '/v1/departmentinfo/editDepartment', 
    qs.stringify({
      oldDepartmentName: originalName, // 原始部门名称
      newDepartmentName: saveDepartmentForm.value.departmentName // 新部门名称
    }),
    {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    }
  ).then(response => {
    if (response.data.code === 2000) {
      ElMessage.success('部门名称修改成功');
      dialogNewDepartment.value = false;
      saveDepartmentForm.value = {};
      loadDepartment();
    } else {
      ElMessage.error(response.data.msg);
    }
  }).catch(error => {
    console.error('修改部门失败:', error);
    ElMessage.error('修改部门失败，请重试');
  });
}

</script>

<style scoped>
/* 全局视觉体系 */
:global(body) {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #ffffff;
  font-size: 16px;
}

/* 颜色系统（CSS变量替代SCSS变量） */
:root {
  --primary-gradient: linear-gradient(45deg, #ff6f00 0%, #ffca28 100%);
  --dark-bg: #1a1a1a;
  --table-bg: #2d2d2d;
  --hover-bg: #3d3d3d;
  --border-color: #4a4a4a;
  --text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
  --spacing-base: 1.2rem;
  --spacing-card: 1.2rem;
  --spacing-table: 1.5rem;
}

/* 部门管理页深色主题 */
.head {
  background: var(--primary-gradient);
  color: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}

.headTitle {
  font-size: 22px;
  color: white;
  font-weight: 600;
  text-shadow: var(--text-shadow);
}

/* 卡片容器 */
.el-card {
  margin: var(--spacing-card);
  border-radius: 14px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3);
  background-color: var(--dark-bg);
  color: #fff;
}

/* 表格样式 */
.el-table {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
  background-color: var(--table-bg);
  color: #333333; /* 修改为深灰色字体 */
}

.el-table__row {
  transition: background-color 0.3s ease;
  background-color: var(--table-bg);
  color: #333333; /* 修改为深灰色字体 */
  font-size: 15px;
}

.el-table__row:hover {
  background-color: var(--hover-bg) !important;
}

/* 弹窗样式 */
.el-dialog {
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.5);
  background-color: var(--dark-bg);
  color: #fff;
}

/* 表单样式 */
.el-form-item {
  margin-bottom: var(--spacing-base);
}

.el-form-item label {
  color: #fff;
  font-weight: 600;
  font-size: 15px;
}

.el-input__inner {
  border-radius: 8px;
  border: 1px solid #ffca28;
  transition: all 0.3s ease;
  background-color: #3d3d3d;
  color: #fff;
  font-size: 15px;
  font-weight: 500;
}

/* 按钮样式 */
.el-button--primary {
  background: var(--primary-gradient);
  color: white;
  transition: all 0.3s ease;
  border: none;
  font-weight: 600;
  font-size: 15px;
}

.el-button--primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(255, 202, 40, 0.5);
}

/* 移动端适配 */
@media (max-width: 768px) {
  :global(body) {
    font-size: 15px;
  }
  
  .el-input__inner {
    font-size: 15px;
  }
  
  .el-table__cell {
    font-size: 14px;
  }
}
</style>